package cn.iocoder.yudao.module.infra.controller.admin.base;

import cn.iocoder.yudao.framework.common.exception.BusinessException;
import cn.iocoder.yudao.framework.common.util.validation.ValidationUtils;
import cn.iocoder.yudao.framework.web.core.util.BaseController;
import cn.iocoder.yudao.module.infra.dal.dataobject.base.AmisDO;
import cn.iocoder.yudao.module.infra.service.base.AmisService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/infra/base/amis")
public class AmisController extends BaseController {

    @Resource
    private AmisService amisService;

    @GetMapping(value = "/getAmis/{type}", produces = "application/json")
    public AmisDO getAmis(@PathVariable String type) {

        AmisDO sysAmisData = amisService.getByType(type);
        if (sysAmisData == null) {
            sysAmisData = new AmisDO();
            sysAmisData.setType(type);
            sysAmisData.setJsonData("{" +
                    "  \"type\": \"page\"," +
                    "  \"regions\": [" +
                    "    \"body\"" +
                    "  ]" +
                    "}");
        }
        return sysAmisData;
    }

    @PostMapping(value = "/saveAmis", produces = "application/json")
    public void saveAmis(@RequestBody AmisDO amis) {
        ValidationUtils.validNotBeNull(amis, "amis");
        LambdaQueryWrapper<AmisDO> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(AmisDO::getType, amis.getType());
        AmisDO sysAmisData = amisService.getOne(queryWrapper);
        if (sysAmisData == null) {
            throw new BusinessException("Amis-{}不存在").addAttachment(amis.getType());
        }
        sysAmisData.setJsonData(amis.getJsonData());
        sysAmisData.setUpdater(getLoginUserId().toString());
        amisService.updateById(sysAmisData);
    }
}
